package cn.acewill.yxd.yunxundian.ui.sign;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.ColorSpace;
import android.graphics.Rect;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.zyf.vc.ui.PlayVideoActiviy;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.DbException;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.adapter.BaseMediaAdapter;
import cn.acewill.yxd.yunxundian.adapter.ImgGradeAdapter;
import cn.acewill.yxd.yunxundian.adapter.MainPageFragmentAdapter;
import cn.acewill.yxd.yunxundian.componet.MyScrollGridView;
import cn.acewill.yxd.yunxundian.model.RMain;
import cn.acewill.yxd.yunxundian.model.Schedule;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.model.rJson;
import cn.acewill.yxd.yunxundian.model.sType;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.RMainUtils;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.ui.user.ImageViewPagerActivity;
import cn.acewill.yxd.yunxundian.ui.user.YxdAbstractPhtotoActivity;
import cn.acewill.yxd.yunxundian.utils.CacheActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;

/**
 * Created by xxx on 2018/1/18.
 */

public class EvaBackUpActivity extends YxdAbstractPhtotoActivity implements View.OnClickListener,TextWatcher{

    private int VIDEO_TAG = 0;
    private int IMG_TAG = 1;

    private CheckBox backUpBtn,videoBtn,imgBtn;
    private ViewPager viewPager;
    private int schId;
    private RMain.TablesBean.RowsBean.Q2Bean q2Bean;
    private EditText backUpText;
    private MyScrollGridView imgRecycle;
    private MyScrollGridView videoRecycle;
    private List<RMain>rMains;
    private CheckBox addFollow;
    private TextView disCheckFollow;
    private RecognizerDialog iatDialog=null;
    private BaseMediaAdapter imgAdapter;
    private BaseMediaAdapter videoAdapter;
    private String shopName = "";
    private List<String> jpgList = new ArrayList<>();
    private List<String> videoList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_eva_backup);
        CacheActivity.addActivity(this);
        initView();
        initRMain();
    }

    @Override
    public void onPhotoSelected(String resultPath) {
        try {
            tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",schId)
                    .and("rRowId","=",q2Bean.getID()).findFirst();
            if (rr!=null){
                if (rr.getJpgStr()!=null){
                    rr.setJpgStr(rr.getJpgStr()+resultPath);
                }else{
                    rr.setJpgStr(resultPath);
                }
                db.saveOrUpdate(rr);
                jpgList = splitListViewPicString(rr.getJpgStr());
                setImgAdater(jpgList);
            }else{
                RMain.TablesBean.RowsBean rowsBean = RMainUtils.getInstance().getRowByMInId(rMains,q2Bean.getID());
                if (rowsBean!=null){
                    double score = rowsBean.getRItems().get(0).getScore();
                    int scoreId = rowsBean.getRItems().get(0).getID();
                    if (q2Bean.getItemType() == 1|| TextUtils.isEmpty(q2Bean.getItemType()+"")){
                        rr = new tempLostRR(MainActivity.id,schId,q2Bean.getID(),score,scoreId, BaseActivity.getNowDate(),
                                "",resultPath,q2Bean.getReportRowName(), 1,"",true);
                    }else{
                        rr = new tempLostRR(MainActivity.id,schId,q2Bean.getID(),q2Bean.getMaxScore(),0, BaseActivity.getNowDate(),
                                "",resultPath,q2Bean.getReportRowName(), 2,"",true);
                    }
                    db.saveOrUpdate(rr);
                    jpgList = splitListViewPicString(rr.getJpgStr());
                    setImgAdater(jpgList);
                }else{
                    showToast(this,"数据错误");
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onVideoRecode(String resultPath) {
        try {
            tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",schId)
                    .and("rRowId","=",q2Bean.getID()).findFirst();
            if (rr!=null){
                if (resultPath.length()>0){
                    rr.setVideoStr(resultPath);
                    db.saveOrUpdate(rr);
                    videoList = splitListViewPicString(resultPath+",");
                    setVideoAdapter(videoList);
                }
            }else{
                RMain.TablesBean.RowsBean rowsBean = RMainUtils.getInstance().getRowByMInId(rMains,q2Bean.getID());
                if (rowsBean!=null){
                    double score = rowsBean.getRItems().get(0).getScore();
                    int scoreId = rowsBean.getRItems().get(0).getID();
                    if (q2Bean.getItemType() == 1|| TextUtils.isEmpty(q2Bean.getItemType()+"")){
                        rr = new tempLostRR(MainActivity.id,schId,q2Bean.getID(),score,scoreId, BaseActivity.getNowDate(),
                                "","",q2Bean.getReportRowName(), 1,resultPath,true);
                    }else{
                        rr = new tempLostRR(MainActivity.id,schId,q2Bean.getID(),q2Bean.getMaxScore(),0, BaseActivity.getNowDate(),
                                "","",q2Bean.getReportRowName(), 2,resultPath,true);
                    }
                    db.saveOrUpdate(rr);
                    videoList = splitListViewPicString(rr.getVideoStr()+",");
                    setVideoAdapter(videoList);
                }else{
                    showToast(EvaBackUpActivity.this,"数据错误");
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    private void initView(){
        schId = getIntent().getIntExtra("schId",0);
        q2Bean = (RMain.TablesBean.RowsBean.Q2Bean) getIntent().getSerializableExtra("q2Bean");
        String name = getIntent().getStringExtra("name");
        Toolbar toolbar = findViewById(R.id.myToolBar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        backUpText = findViewById(R.id.backUpText);
        backUpText.addTextChangedListener(this);
        TextView title = findViewById(R.id.textTitle);
        title.setText(q2Bean.getSName()+q2Bean.getReportRowName());
        addFollow = findViewById(R.id.addFollow);
        addFollow.setOnClickListener(this);
        TextView majorName = findViewById(R.id.majorName);
        if (name!=null){
            if (name.length()>7){
                StringBuffer buffer = new StringBuffer();
                buffer.append(name.substring(0,6)).append("..");
                majorName.setText(buffer.toString());
            }else{
                majorName.setText(name);
            }
        }else{
            majorName.setText("");
        }
        majorName.setText(name);
        disCheckFollow= findViewById(R.id.disCheckFollow);
        disCheckFollow.setOnClickListener(this);
        ImageView voiceInput = findViewById(R.id.voiceInput);
        voiceInput.setOnClickListener(this);
        imgRecycle = findViewById(R.id.imgRecycle);
        videoRecycle = findViewById(R.id.videoRecycle);
        try {
            tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",schId)
                    .and("rRowId","=",q2Bean.getID()).findFirst();
            initImgAdapter(rr);
            initVideoAdapter(rr);
            if (rr!=null){
                if (rr.isFbIsCheck()){
                    addFollow.setChecked(true);
                    addFollow.setEnabled(false);
                    disCheckFollow.setVisibility(View.VISIBLE);
                }else{
                    addFollow.setChecked(false);
                    addFollow.setEnabled(true);
                    disCheckFollow.setVisibility(View.GONE);
                }
                if (rr.getDescStr()!=null&&!TextUtils.isEmpty(rr.getDescStr())){
                    backUpText.setText(rr.getDescStr());
                }
            }else{
                addFollow.setChecked(false);
                disCheckFollow.setVisibility(View.GONE);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void initImgAdapter(tempLostRR rr){
        if (rr!=null){
            if (rr.getJpgStr()!=null&& !TextUtils.isEmpty(rr.getJpgStr())){
                jpgList = splitListViewPicString(rr.getJpgStr());
            }
        }
        setImgAdater(jpgList);

    }
    /**
     * 拆分图片的路径，并添加到listview中
     *
     * @param fileString
     * @return
     */
    public List<String> splitListViewPicString(String fileString) {
        String[] everyPicFile = fileString.split(",");
        List<String> imgList = new ArrayList<String>();
        for (String everyPic : everyPicFile) {
            if (!TextUtils.isEmpty(everyPic)) {
                imgList.add(everyPic);
            }
        }
        return imgList;
    }

    public void initVideoAdapter(tempLostRR rr){
        String[] str = new String[0];
        if (rr!=null){
            if (rr.getVideoStr()!=null&&!TextUtils.isEmpty(rr.getVideoStr())){
               videoList = splitListViewPicString(rr.getVideoStr()+",");
            }
        }
        setVideoAdapter(videoList);

    }

    public void setImgAdater(List<String> str){
        imgAdapter = new BaseMediaAdapter(this,str,IMG_TAG);
        imgRecycle.setAdapter(imgAdapter);
        imgRecycle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",schId)
                            .and("rRowId","=",q2Bean.getID()).findFirst();
                    int maxJpgCount = 9;
                        if (rr!=null){
                            maxJpgCount = getSelectJpgCount(rr);
                            if (position == (9-maxJpgCount)){
                                showPopWin(EvaBackUpActivity.this,shopName,true,maxJpgCount);
                            }else{
                                startActivity(new Intent(EvaBackUpActivity.this,ImageViewPagerActivity.class)
                                        .putExtra("filepath",rr.getJpgStr() )
                                        .putExtra("position",position));
                            }
                            return;
                        }
                        showPopWin(EvaBackUpActivity.this,shopName,true,maxJpgCount);
//
//                    }else{
//                        //查看图片
//                        maxJpgCount = getSelectJpgCount(rr);
//                        if (position == (9-maxJpgCount)){
//                            showPopWin(EvaBackUpActivity.this,shopName,true,maxJpgCount);
//                        }else{
//                            startActivity(new Intent(EvaBackUpActivity.this,ImageViewPagerActivity.class)
//                                    .putExtra("filepath",rr.getJpgStr() )
//                                    .putExtra("position",position));
//                        }
//
//                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }

        });
        imgRecycle.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",schId)
                            .and("rRowId","=",q2Bean.getID()).findFirst();
                   int maxJpgCount = getSelectJpgCount(rr);
                    if (position!=(9-maxJpgCount)) {
                        DelPicListItem(position, rr);
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
                return true;
            }
        });

        imgAdapter.notifyDataSetChanged();
    }
    public void setVideoAdapter(List<String> str){
        videoAdapter = new BaseMediaAdapter(this,str,VIDEO_TAG);
        videoRecycle.setAdapter(videoAdapter);
        videoRecycle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",schId)
                            .and("rRowId","=",q2Bean.getID()).findFirst();
                    if (rr!=null){
                        //  查看视频
                        if (rr.getVideoStr()!=null&&rr.getVideoStr().length()>1){

                            startActivity(new Intent(EvaBackUpActivity.this,PlayVideoActiviy.class)
                                    .putExtra("file_path",videoList.get(position)).putExtra("code_play",2));
                        }else{
                            showVideoPop(EvaBackUpActivity.this);
                        }
                        return;
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
//                else{
//                    //查看视频
//                    startActivity(new Intent(EvaBackUpActivity.this,PlayVideoActiviy.class)
//                            .putExtra("file_path",videoList.get(position-1)).putExtra("code_play",2));
//
//                }
        });
        videoRecycle.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                    try {
                        tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",schId)
                                .and("rRowId","=",q2Bean.getID()).findFirst();
                        if (rr.getVideoStr()!=null&&rr.getVideoStr().length()>1) {
                            DelVidListItem(position,rr);
                        }
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                return true;
            }
        });
        videoAdapter.notifyDataSetChanged();
    }
    public void initRMain(){
        try {
            Schedule schedule = db.selector(Schedule.class).where("ID","=",schId).findFirst();
            int shopId = schedule.getShopID();
            if(shopId>0) {
                Shop shop = db.selector(Shop.class).where("ID", "=", shopId).findFirst();
                shopName = shop.getShopName();
            }
            sType type=db.selector(sType.class).where("ID","=",schedule.getSTypeID()).findFirst();
            rJson rmian = db.selector(rJson.class).where("ID", "=", type.getReportId()).findFirst();
            if (rmian==null){
                showToast(this,"数据错误");
                finish();
            }
            String json= rmian.getjSon();
            Gson gson=new Gson();
            Type typeList = new TypeToken<ArrayList<RMain>>() {
            }.getType();
            rMains = gson.fromJson(pubClass.convertToArrayJsonNormal(json), typeList);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    private void DelPicListItem(final int position, final tempLostRR rr) {

        MaterialDialogUtils.showMaterialDialog(this, "是否删除照片", "确定", "取消", true,false, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
                jpgList.remove(position);
                String newAllvideoFile="";
                for (int i=0;i<jpgList.size();i++){
                    newAllvideoFile+=jpgList.get(i)+",";
                }
                rr.setJpgStr(newAllvideoFile);
                try {
                    db.saveOrUpdate(rr);
                    setImgAdater(jpgList);
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
            }
        });
    }
    private void DelVidListItem(final int position, final tempLostRR rr){
        MaterialDialogUtils.showMaterialDialog(this, "是否删除视频", "确定", "取消", true,false, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
                videoList.remove(position);
                String newAllvideoFile="";
                for (int i=0;i<videoList.size();i++){
                    newAllvideoFile+=videoList.get(i)+",";
                }
                rr.setVideoStr(newAllvideoFile);
                try {
                    db.saveOrUpdate(rr);
                    setVideoAdapter(videoList);
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
        }, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.addFollow:
                try {
                    tempLostRR rr = db.selector(tempLostRR.class).where("schId","=",schId)
                            .and("rRowId","=",q2Bean.getID()).findFirst();
                    if (rr!=null){
                        if (rr.isFbIsCheck()){
                            return;
                        }else{
                            rr.setFbIsCheck(true);
                            addFollow.setChecked(true);
                            addFollow.setEnabled(false);
                            disCheckFollow.setVisibility(View.VISIBLE);
                        }
                    }
//                    else{
//                        addFollow.setEnabled(true);
//                        disCheckFollow.setVisibility(View.VISIBLE);
//                        RMain.TablesBean.RowsBean rowsBean = RMainUtils.getInstance().getRowByMInId(rMains,q2Bean.getID());
//                        int scoreId = rowsBean.getRItems().get(0).getID();
//                        if (q2Bean.getItemType() == 1|| TextUtils.isEmpty(q2Bean.getItemType()+"")){
//                            rr = new tempLostRR(MainActivity.id,schId,q2Bean.getID(),q2Bean.getMaxScore(),scoreId, BaseActivity.getNowDate(),
//                                    "","",q2Bean.getReportRowName(),1,q2Bean.getIsPoint(),"",true,true);
//                        }else{
//                            rr = new tempLostRR(MainActivity.id,schId,q2Bean.getID(),q2Bean.getMaxScore(),0, BaseActivity.getNowDate(),
//                                    "","",q2Bean.getReportRowName(), 2,q2Bean.getIsPoint(),"",true,true);
//                        }
//                    }
                    db.saveOrUpdate(rr);
                } catch (DbException e) {
                    e.printStackTrace();
                }

                break;

            case R.id.disCheckFollow:
                try {
                    tempLostRR  rr = db.selector(tempLostRR.class).where("schId","=",schId)
                            .and("rRowId","=",q2Bean.getID()).findFirst();
                    if (rr!=null){
                        rr.setFbIsCheck(false);
                        addFollow.setChecked(false);
                        addFollow.setEnabled(true);
                        disCheckFollow.setVisibility(View.GONE);
                        db.saveOrUpdate(rr);
                    }
                } catch (DbException e) {
                    e.printStackTrace();
                }

                break;
            case R.id.voiceInput:
                if (iatDialog != null) {
                    iatDialog.cancel();
                    iatDialog.destroy();
                }
                startDialogOnline();
                break;
        }
    }

    public void startDialogOnline() {
        //1.创建SpeechRecognizer对象，第二个参数：本地听写时传InitListener
        iatDialog = new RecognizerDialog(this, mInitListener);
        //2.设置听写参数

        iatDialog.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        iatDialog.setParameter(SpeechConstant.ACCENT, "mandarin ");


        //3.设置回调接口
        iatDialog.setListener(new RecognizerDialogListener() {
            @Override
            public void onResult(RecognizerResult recognizerResult, boolean b) {
                if (!b) {
                    String json = recognizerResult.getResultString();

                    String str = jsonToHua(json);
                    backUpText.append(str);
                    //Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(SpeechError speechError) {
                //Log.e("error", speechError.toString());
            }
        });
        //4.开始听写
        iatDialog.show();
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {

        @Override
        public void onInit(int code) {
            //Log.i("tag", "SpeechRecognizer init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                Toast.makeText(EvaBackUpActivity.this,"语音初始化失败",Toast.LENGTH_SHORT).show();
                //Log.e("tag", "初始化失败，错误码：" + code);
            }
        }
    };


    public String jsonToHua(String json)
    {
        StringBuilder retStr= new StringBuilder();
        try {
            JSONObject result = new JSONObject(json);
            JSONArray nameList = result.getJSONArray("ws");//获取JSONArray
            for(int i=0;i<nameList.length();i++)
            {
                JSONObject jo=nameList.getJSONObject(i);
                JSONArray ja=jo.getJSONArray("cw");
                for(int j=0;j<ja.length();j++)
                {
                    retStr.append(ja.getJSONObject(j).getString("w"));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return retStr+".";

    }

    /*计算选取的照片的额数量*/
    public int getSelectJpgCount(tempLostRR rr){
        if (rr.getJpgStr()!=null&&rr.getJpgStr().length()>0){
            String[] array = rr.getJpgStr().split(",");
            if (array.length<9){
                return 9-array.length;
            }else{
                return 0;
            }
        }else{
            return 9;

        }
    }


    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        Log.e("===ssss===",s.toString());
        try {
            tempLostRR  rr = db.selector(tempLostRR.class).where("schId","=",schId)
                    .and("rRowId","=",q2Bean.getID()).findFirst();
            if (rr!=null){
                rr.setDescStr(s.toString());
                db.saveOrUpdate(rr);
            }
//            else{
//                RMain.TablesBean.RowsBean rowsBean = RMainUtils.getInstance().getRowByMInId(rMains,q2Bean.getID());
//                int scoreId = rowsBean.getRItems().get(0).getID();
//                if (q2Bean.getItemType() == 1|| TextUtils.isEmpty(q2Bean.getItemType()+"")){
//                    rr = new tempLostRR(MainActivity.id,schId,q2Bean.getID(),q2Bean.getMaxScore(),scoreId, BaseActivity.getNowDate(),
//                            s.toString(),"",q2Bean.getReportRowName(), 1,q2Bean.getIsPoint(),"",true,true);
//                }else{
//                    rr = new tempLostRR(MainActivity.id,schId,q2Bean.getID(),q2Bean.getMaxScore(),0, BaseActivity.getNowDate(),
//                            s.toString(),"",q2Bean.getReportRowName(), 2,q2Bean.getIsPoint(),"",true,true);
//                }
//                db.saveOrUpdate(rr);
//            }

        } catch (DbException e) {
            e.printStackTrace();
        }
    }
}
